﻿using System.Net.WebSockets;
using System.Text;

namespace WebApi.Controllers
{
    public class WebSocketApi
    {
        static Uri clientUri = new Uri("wss://www.lilongfei.club:1994"); // WebSocket server address https 使用
                                                                         //static Uri clientUri = new Uri("ws://www.lilongfei.club:1994"); // WebSocket server address http 使用

        static ClientWebSocket clientWebSocket = new ClientWebSocket();

        #region 客户端 IIS
        public static async Task WebSocketStart()
        {
            try
            {
                //只进行一次链接请求
                if (clientWebSocket.State != WebSocketState.Open)
                {
                    //将代理器设为空
                    clientWebSocket.Options.Proxy = null;
                    //链接 IIS服务器
                    await clientWebSocket.ConnectAsync(clientUri, CancellationToken.None);
                }

                Console.WriteLine("Connected to the WebSocket server.");

                // Send a message to the server
                string messageToSend = "Hello, server!";
                byte[] sendBuffer = Encoding.UTF8.GetBytes(messageToSend);
                await clientWebSocket.SendAsync(new ArraySegment<byte>(sendBuffer), WebSocketMessageType.Text, true, CancellationToken.None);

                // Receive and handle the server's response
                byte[] receiveBuffer = new byte[1024];
                WebSocketReceiveResult receiveResult = await clientWebSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
                string receivedMessage = Encoding.UTF8.GetString(receiveBuffer, 0, receiveResult.Count);
                Console.WriteLine($"Received: {receivedMessage}");
            }
            catch (Exception e)
            {
                await CloseWebSocket(clientWebSocket);
                Console.WriteLine(e);
                throw;
            }

        }

        //关闭 WebSocket 链接
        static async Task CloseWebSocket(ClientWebSocket clientWebSocket)
        {
            byte[] closeBuffer = Encoding.UTF8.GetBytes("Connection closing...");
            WebSocketCloseStatus closeStatus = WebSocketCloseStatus.NormalClosure;
            string closeDescription = "Connection closed gracefully";
            CancellationToken ct = CancellationToken.None;

            await clientWebSocket.CloseOutputAsync(closeStatus, closeDescription, ct);
            WebSocketReceiveResult result = await clientWebSocket.ReceiveAsync(new ArraySegment<byte>(new byte[1024]), ct);
            await clientWebSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, ct);
        }

        #endregion
    }

}
